package com.yy.json;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaBeanSerializer implements ObjectSerializer {
    private List<FieldSerializer> mFieldSerializers;

    public JavaBeanSerializer(Class<?> beanType) {
        //1.查找所有符合条件的函数 getXx isXx
        //2.查找自己和父类的public field
        Map<String, Field> fieldMap = new HashMap<>();
        Utils.parseAllFieldToCache(beanType, fieldMap);
        mFieldSerializers = Utils.computeGetters(beanType, fieldMap);

    }

    @Override
    public void serializer(JsonConfig config, StringBuilder out, Object object) {
        out.append("{");
        int i = 0;
        for (FieldSerializer fieldSerializer : mFieldSerializers) {
            if (i != 0) {
                out.append(",");
            }
            String serializer = fieldSerializer.serializer(config, object);
            out.append(serializer);
            //如果属性没有值,返回""
            if (serializer.isEmpty()) {
                i = 0;
            } else {
                i = 1;
            }
        }
        out.append("}");
    }
}
